#include "KnowledgeBaseWriterFile.h"
#include "ToStr.h"
#include <iomanip>
#include <sstream>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Factory < KnowledgeBaseWriterInterface > KnowledgeBaseWriterFile::factory;

KnowledgeBaseWriterFile::KnowledgeBaseWriterFile ()
{
}

KnowledgeBaseWriterInterfacePtr KnowledgeBaseWriterFile::Spawn ( TextStreamInterfacePtr argTextStream )
{
	KnowledgeBaseWriterFilePtr writer ( factory.CreateNewObject < KnowledgeBaseWriterFile > () );
	writer->textStream = argTextStream;
	return writer;
}

void KnowledgeBaseWriterFile::CheckInnocence ()
{
	assert ( factory.ObjectsCount () == 0 );
}
	
void KnowledgeBaseWriterFile::Write ( KnowledgeBaseMemoryInterfacePtr memory )
{
	const int MAX_TEXT_LENGTH = 62;
	
	for ( int globalAddress = 1; globalAddress < memory->ElementsCount (); globalAddress++ )
	{
		KnowledgeBaseElementInterfacePtr element = memory->Element ( globalAddress );
		textStream->WriteString ( ToStr ( globalAddress ) );
		textStream->WriteString ( ToStr ( element->SeniorKey () ) );
		textStream->WriteString ( ToStr ( element->SeniorType () ) );
		if ( globalAddress == memory->TypeRootAddress () || globalAddress == memory->ValueRootAddress () )
			textStream->WriteString ( std::string ( MAX_TEXT_LENGTH, ' ' ) );
		else if ( int ( element->LexemText ().size () ) <= MAX_TEXT_LENGTH )
		{
			textStream->WriteString ( element->LexemText () );
			textStream->WriteString ( std::string ( MAX_TEXT_LENGTH - element->LexemText ().size (), ' ' ) );
		}
		else
			textStream->WriteString ( element->LexemText ().substr ( 0, MAX_TEXT_LENGTH ) );
		textStream->WriteString ( ToStr ( element->UpperBranch () ) );
		textStream->WriteString ( ToStr ( element->LowerBranch () ) );
		textStream->WriteString ( ToStr ( element->NextLevel () ) );
		textStream->WriteString ( ToStr ( element->Synonym () ) );
		textStream->WriteString ( ToStr ( element->AdjacentAscending () ) );
		textStream->WriteString ( ToStr ( element->AdjacentDescending () ) );
		textStream->WriteString ( ToStr ( element->BeforeAdjacentAscending () ) );
		textStream->WriteString ( ToStr ( element->BeforeAdjacentDescending () ) );
		textStream->WriteString ( ToStr ( element->GreaterAscending () ) );
		textStream->WriteString ( ToStr ( element->GreaterDescending () ) );
		textStream->WriteString ( ToStr ( element->LesserAscending () ) );
		textStream->WriteString ( ToStr ( element->LesserDescending () ) );
		textStream->WriteString ( "\n\r" );
	}
}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
